﻿using System;
using MvvmFx.Common.ViewModels.Commands;

namespace MvvmFx.Common.ViewModels.Behaviors.ProcessManagement
{
    public class GoToStepCommand : ViewModelCommand
    {
        private readonly ProcessService _processService;

        public GoToStepCommand(ProcessService processService)
        {
            _processService = processService;

            _processService.NewPropertyObserver()
                .AddHandler("CurrentStep", p => OnCanExecuteChanged());
        }

        protected override void OnExecute(object parameter)
        {
            string key = parameter.ToString();
            _processService.Show(key);
        }

        protected override bool OnCanExecute(object parameter)
        {
            if (_processService.HasCurrentStep)
            {
                string key = parameter.ToString();

                int currentIndex = _processService.Steps.IndexOf(_processService.CurrentStep);

                for (int i = 0; i < _processService.Steps.Count; i++)
                {
                    var step = _processService.Steps[i];
                    if (step.Key == key)
                    {
                        if (i <= currentIndex)
                            return true;
                    }
                }
            }

            return false;
        }
    }
}